﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports ISNet.WebUI.WebTreeView
Imports log4net

Partial Class B05_FixMoneyLimit
    Inherits System.Web.UI.Page
    Dim cmmtcode As String = ""
    Public AlertText As String
    Public ScriptText As String

    Private Shared logger As ILog = LogManager.GetLogger("B05_FixMoneyLimit")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        cmmtcode = Session("CMMT_OT_CODE")
        ' PlanYearsTxt.Text = Session("PlanYear")
        'Session("Versions") = 1
        VersionTxt.Text = Session("Versions")
        'Session("users") = "bb9222"
        'Session.Add("PlanYear", 2557)
        PlanYearsTxt.Text = Session("PlanYear")
        'If Session("FCTR") Is Nothing Then
        '    Response.Redirect("Selector.aspx?type=1")
        'End If
        'If Session("users") Is Nothing Then
        '    Response.Redirect("LoginForm.aspx")
        'End If
        GenerateValues()

        If IsPostBack = False Then
            Session.Remove("Search")
            Session.Remove("search_fctr")


            Label1.Text = "ระบบจัดทำงบประมาณ >> จัดทำงบประมาณ >> แบบฟอร์มกำหนดกรอบงบประมาณ"
            'If Session("Versions") = 1 Then
            '    div1.Visible = False
            '    div2.Visible = False
            '    SearhBtn.Visible = False
            '    WebTreeView1.Visible = False
            '    WebTreeView2.Visible = False
            '    WebTreeView3.Visible = False
            'End If


            Dim adapter As New MassChangeDSTableAdapters.CmmtsTableAdapter
            Dim datatable As New MassChangeDS.CmmtsDataTable
            datatable = adapter.GetData(Session("PlanYear"))
            ms9.DataValueField = "CmmtCode"
            ms9.DataTextField = "Description"
            ms9.DataSource = datatable
            ms9.DataBind()
            'GenerateValues()
        End If
        'If WebGrid1.IsFlyPostBack = False Then
        '    PlotNode()
        'End If

        'WebGrid1.ClientAction.Refresh()
    End Sub

    'Protected Sub WebGrid1_InitializeColumn(sender As Object, e As ColumnEventArgs) Handles WebGrid1.InitializeColumn
    '    If e.Column.ColumnType = ColumnType.CheckBox And WebGrid1.RootTable.Rows.Count = 0 Then
    '        e.Column.IsRowChecker = False
    '        e.Column.Width = 24
    '        e.Column.Caption = " "
    '    End If
    'End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        Dim adapter As New FixMoneyLimitTableAdapters.BudgetDetailsTableAdapter
        Dim datatable As New FixMoneyLimit.BudgetDetailsDataTable

        Dim prefil As String = ""
        prefil = Session("prefilter")
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim sql As String = ""
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
                sql += " WHERE 1 = 1 "
                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value
                If TabContainer2.ActiveTab.ID = TabPanel3.ID Then
                    If WebCombo4.Value <> "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode Between "
                        sql += WebCombo4.Value & " AND "
                        sql += WebCombo5.Value & " "
                    ElseIf WebCombo4.Value <> "" And WebCombo5.Value = "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo4.Value & " "
                    ElseIf WebCombo4.Value = "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo5.Value & " "
                    End If
                ElseIf TabContainer2.ActiveTab.ID = TabPanel4.ID Then
                    If hdf2.Value.ToString <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode IN ("
                        Dim Numx As Array = hdf2.Value.Split(",")
                        For i = 0 To Numx.Length - 1
                            If Val(Numx(i)) <> 0 Then
                                If i <> 0 Then
                                    sql += ","
                                End If
                                sql += Numx(i).ToString
                            End If

                        Next
                        sql += ") "
                    End If
                End If

                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                ' sql += " AND FormId = 'F01' "
                'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                If fctr <> "" Then
                    If fctr <> "0" Then
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                    Else
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
                    End If
                Else
                    If prefil <> "" Then
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "

                    End If

                End If
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
                adapter.GetDataByFilter(datatable, sql)
                'Response.Write(sql)

            ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
                sql += " WHERE 1 = 1 "
                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode IN (SELECT FundCenter_FundCenterCode FROM FundCenterHierarchies "
                'sql += " WHERE FundCenter_FundCenterCode = " & Val(WebCombo3.Value) & " OR ParentFundCenterHierarchy_Id = " & Val(WebCombo3.Value) & ") "
                If TabContainer2.ActiveTab.ID = TabPanel3.ID Then
                    If WebCombo4.Value <> "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode Between "
                        sql += WebCombo4.Value & " AND "
                        sql += WebCombo5.Value & " "
                    ElseIf WebCombo4.Value <> "" And WebCombo5.Value = "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo4.Value & " "
                    ElseIf WebCombo4.Value = "" And WebCombo5.Value <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode = "
                        sql += WebCombo5.Value & " "
                    End If
                ElseIf TabContainer2.ActiveTab.ID = TabPanel4.ID Then
                    If hdf2.Value.ToString <> "" Then
                        sql += " AND BudgetDetails.Cmmt_CmmtCode IN ("
                        Dim Numx As Array = hdf2.Value.Split(",")
                        For i = 0 To Numx.Length - 1
                            If Val(Numx(i)) <> 0 Then
                                If i <> 0 Then
                                    sql += ","
                                End If
                                sql += Numx(i).ToString
                            End If

                        Next
                        sql += ") "
                    End If
                End If
                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                '  sql += " AND FormId = 'F01' "
                'sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
                If fctr <> "" Then
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                Else
                    If prefil <> "" Then
                        sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
                    End If

                End If
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
                adapter.GetDataByFilter(datatable, sql)
                'Response.Write(prefil)

            End If

            'Response.Write(sql)
            'datatable.Columns("PlanYear").AllowDBNull = True
            'datatable.Columns("BaseYear").AllowDBNull = True
            'datatable.Columns("Version").AllowDBNull = True
            'datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
            'datatable.Columns("OldAssetNo").AllowDBNull = True
            'datatable.Columns("FundCenter_PlanYear").AllowDBNull = True
            'datatable.Columns("Element8").AllowDBNull = True
            'datatable.Columns("Element9").AllowDBNull = True
            'datatable.Columns("Fund_FundCode").AllowDBNull = True
            'datatable.Columns("Fund_PlanYear").AllowDBNull = True

            datatable.Columns("Id").ReadOnly = False
            For i = 0 To datatable.Columns.Count - 1
                datatable.Columns(i).AllowDBNull = True
            Next

            e.DataSource = datatable

            If datatable.Count > 0 Then
                Dim total As Decimal
                total = datatable.Compute("Sum(Amount)", "")
                TextBox2.Text = Format(total, "#,###.00")
            Else
                TextBox2.Text = "0.00"
            End If

            'datatable = adapter.GetDataByMultiple(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))
        Else
            Dim sql As String = ""

            sql += " WHERE 1 = 1 "
            'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value)
            sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
            'sql += " AND FormId = 'F01' "
            ' sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
            If prefil <> "" Then
                sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
            End If
            sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
            sql += " ORDER BY BudgetDetails.FundCenter_FundCenterCode,BudgetDetails.Id"
            adapter.GetDataByFilter(datatable, sql)
            'Response.Write(sql)
            'datatable = adapter.GetDataByMultiple2(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))



            'datatable.Columns("PlanYear").AllowDBNull = True
            'datatable.Columns("BaseYear").AllowDBNull = True
            'datatable.Columns("Version").AllowDBNull = True
            'datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
            'datatable.Columns("OldAssetNo").AllowDBNull = True
            'datatable.Columns("FundCenter_PlanYear").AllowDBNull = True
            'datatable.Columns("Element8").AllowDBNull = True
            'datatable.Columns("Element9").AllowDBNull = True
            'datatable.Columns("AssetNo").AllowDBNull = True
            'datatable.Columns("ProductCode").AllowDBNull = True
            'datatable.Columns("CmmtCode").AllowDBNull = True
            'datatable.Columns("Cmmt_PlanYear").AllowDBNull = True
            'datatable.Columns("Fund_PlanYear").AllowDBNull = True
            'datatable.Columns("Fund_FundCode").AllowDBNull = True
            'datatable.Columns("CmmtDetail_Id").AllowDBNull = True
            'datatable.Columns("Project_FundCenterCode").AllowDBNull = True
            'datatable.Columns("Project_PlanYear").AllowDBNull = True
            'datatable.Columns("Project_ProjectCode").AllowDBNull = True
            'datatable.Columns("Activity_ActivityCode").AllowDBNull = True
            'datatable.Columns("ActivityType_ActivityTypeCode").AllowDBNull = True
            'datatable.Columns("ActivityType_PlanYear").AllowDBNull = True
            'datatable.Columns("ProductItemNo").AllowDBNull = True
            'datatable.Columns("FunctionalArea").AllowDBNull = True
            'datatable.Columns("TmpFundedProgram").AllowDBNull = True
            'datatable.Columns("FundedProgram").AllowDBNull = True
            'datatable.Columns("FndPrgGenFlag").AllowDBNull = True
            'datatable.Columns("FormId").AllowDBNull = True
            'datatable.Columns("Identification").AllowDBNull = True
            'datatable.Columns("PricePerUnit").AllowDBNull = True
            'datatable.Columns("ReplaceQuantity").AllowDBNull = True
            'datatable.Columns("NewQuantity").AllowDBNull = True
            'datatable.Columns("Amount").AllowDBNull = True

            datatable.Columns("Id").ReadOnly = False

            For i = 0 To datatable.Columns.Count - 1
                datatable.Columns(i).AllowDBNull = True
            Next

            'Response.Write(Val(Session("FCTR")))
            e.DataSource = datatable

            If datatable.Count > 0 Then
                Dim total As Decimal
                total = datatable.Compute("Sum(Amount)", "")
                TextBox2.Text = Format(total, "#,###.00")
            Else
                TextBox2.Text = "0.00"
            End If
            'Response.Write(prefil)
        End If




    End Sub

    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        'Exit Sub
        If e.Row.Type = RowType.Record Then

            'e.Row.Cells(0).ForceNoEdit = True
            e.Row.Cells(1).ForceNoEdit = True
            e.Row.Cells(2).ForceNoEdit = True
            e.Row.Cells(3).ForceNoEdit = True

            e.Row.Cells(6).ForceNoEdit = True

            'Dim funCenterPro As String = e.Row.GetDataRow("Projects_FundCenterCode2")
            'If funCenterPro = "0" Then
            '    e.Row.Cells(16).ForceNoEdit = True
            '    e.Row.Cells(16).Style.BackColor = Drawing.Color.Gray
            'End If
        End If

    End Sub


    Protected Sub FundCenterCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles FundCenterCombo.InitializeDataSource
        Dim ds As New DataSet
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If fctr <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & fctr & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
            'Response.Write(sql & "<br />")
        Else
            'ds = PublicFunction.GetChild2(Session("users"))
            'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
            'e.DataSource = ds
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If prefil <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
        End If

    End Sub

    Protected Sub CmmtCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles CmmtCombo.InitializeDataSource
        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable
        dt = adap.GetData(Val(Session("PlanYear")))
        e.DataSource = dt

    End Sub



    Protected Sub WebGrid1_AddRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim adapter As New FixMoneyLimitTableAdapters.BudgetDetailsTableAdapter
        Dim id As Decimal
        'Dim adapter2 As New BasicDataTableAdapters.CmmtDetailsTableAdapter
        'Dim cmmt_id As Decimal = adapter2.GetCmmtId(Val(e.Row.Cells(2).Value))
        'WebGrid1.ClientAction.Alert(Val(PlanYearsTxt.Text))

        'Dim dataGrid As DataTable
        'dataGrid = CType(WebGrid1.DataSource, DataTable)
        'Dim totalpercent As Integer = 0
        'totalpercent = Val(dataGrid.Compute("Sum(Element8)", ""))
        'If (totalpercent + Val(e.Row.Cells(3).Value)) > 100 Then
        '    Throw New Exception("% ในการกระรวมกันต้องไม่เกิน 100%")
        'End If

        id = adapter.InsertBudget(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, "B05", Session("users"), e.Row.Cells(3).Value, Val(PlanYearsTxt.Text), e.Row.Cells(1).Value, Val(PlanYearsTxt.Text), e.Row.Cells(2).Value, Val(PlanYearsTxt.Text), Val(e.Row.Cells(5).Value), Val(e.Row.Cells(4).Value), Val(e.Row.Cells(6).Value), Date.Now, "2")

        logger.Info("User " & Session("users") & " insert item " & e.Row.Cells(2).Value & " and product " & e.Row.Cells(3).Value & " at fund center " & e.Row.Cells(1).Value)

        'WebGrid1.ClientAction.Alert(id)
        Dim dr As DataRow = e.Row.DataRow
        dr("Id") = id

    End Sub

    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        ' MsgBox(Val(e.Row.Cells(4).Value) & "/" & Val(e.Row.Cells(3).Value))
        Dim id As Decimal
        id = e.Row.KeyValue
        ' MsgBox(e.Row.Cells(3).Value & " " & e.Row.Cells(4).Value & " " & e.Row.Cells(5).Value)
        Dim adapter As New FixMoneyLimitTableAdapters.BudgetDetailsTableAdapter
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        adapter.UpdateBudget(Val(e.Row.Cells(5).Value), Val(e.Row.Cells(4).Value), Val(e.Row.Cells(6).Value), Session("users"), Date.Now, id)
        adapter12.DeleteBID(id)
        logger.Info("User " & Session("users") & " update item " & e.Row.Cells(2).Value & " and product " & e.Row.Cells(3).Value & " at fund center " & e.Row.Cells(1).Value)
    End Sub

    Sub PlotNode()

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()

        Dim adapter As New FundCenterParentTableAdapters.fctr_viewTableAdapter
        Dim dt As New FundCenterParent.fctr_viewDataTable
        dt = adapter.GetDataByUser(Session("users"), Val(PlanYearsTxt.Text))

        Dim root_id As String

        MyNode.Text = "GSB"
        MyNode.Value = "0"
        root_id = "0"

        If dt.Count > 0 Then

            WebTreeView3.Nodes.Add(MyNode)

            Dim rootpath = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            rootpath = FctrClass.GetRootPrefil(Session("users"), Val(Session("planyear")), prefil)
            Dim rootarr() As String = Split(rootpath, ",")
            WebTreeView3.Nodes.Add(MyNode)

            For i = 0 To rootarr.Length - 1
                PlotChild(rootarr(i), MyNode, 1)
            Next
        End If

    End Sub

    Sub PlotChild(ByVal gpath As String, ByRef cnode As WebTreeViewNode, ByVal level As Decimal)
        'Response.Write(gpath & "<br>")
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Hdatatable = Hadapter.GetDataByGPath(gpath, Val(Session("planyear")))

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()
        For Each row As FundCenterParent.FctHRow In Hdatatable


            MyNode.Text = row.Description
            MyNode.Value = row.FundCenter_FundCenterCode

            cnode.Nodes.Add(MyNode)
        Next


        If Len(gpath) >= 10 Then
            Exit Sub
        End If

        Dim hadap2 As New FundCenterParentTableAdapters.UserLikeGpathTableAdapter
        Dim hdt2 As New FundCenterParent.UserLikeGpathDataTable
        Dim sql As String = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")

        Dim pathadd As String = "__"
        'For i = 1 To 4
        sql = ""
        Dim fullpath As String = gpath & pathadd
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " AND grouppath like '" & fullpath & "' "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND Fcth.PlanYear = " & Val(Session("PlanYear"))
        hadap2.GetDataByFilter(hdt2, sql)

        For Each row As FundCenterParent.UserLikeGpathRow In hdt2
            If Len(row.grouppath) <= 10 Then
                PlotChild(row.grouppath, MyNode, level + 1)
            End If

        Next

    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        GenerateValues()
        If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
            Session.Remove("search_fctr")
            If WebCombo1.Value <> "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users")))
            ElseIf WebCombo1.Value <> "" And WebCombo2.Value = "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users")))
            ElseIf WebCombo1.Value = "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users")))
            Else
                Session.Add("search_fctr", Session("prefilter"))
            End If

        ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
            Session.Remove("search_fctr")
            If WebCombo3.Value = "" Then
                Session.Add("search_fctr", Session("prefilter"))
            Else
                Session.Add("search_fctr", FctrClass.GetSubFundCenter(WebCombo3.Value, Session("users"), Session("Planyear"), Session("prefilter")))
            End If

        End If
        Session.Remove("Search")
        Session.Add("Search", "true")
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
        FundCenterCombo.ClearCachedDataSource()
        FundCenterCombo.DataBind()
    End Sub

    Sub GenerateValues()
        If hdf2.Value.Length = 0 And Session("search_fctr") Is Nothing Then
            Session("Search") = "false"
        End If
        Try
            Dim Numx2 As Array = hdf2.Value.Split(",")
            For j = 0 To Numx2.Length - 1
                ms9.Items.FindByValue(Numx2(j).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
    End Sub


    'Protected Sub coppy_btn_Click(sender As Object, e As ImageClickEventArgs) Handles coppy_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.CoppyRow(keyValue)

    '    Next keyValue

    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()

    'End Sub

    'Protected Sub delete_btn_Click(sender As Object, e As ImageClickEventArgs) Handles delete_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.DeleteRow(keyValue)

    '    Next keyValue



    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()

    'End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then
                Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

                For Each keyValue As String In checkedRows

                    adapter.CoppyRow(keyValue)

                Next keyValue
            Else
                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter
                Dim adapter2 As New fundCenterTableAdapters.AttachmentsTableAdapter
                For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                    adapter2.DeleteAttach(keyValue)
                    adapter.DeleteRow(keyValue)
                Next keyValue
            End If

            WebGrid1.ClientAction.Refresh()


        End If

    End Sub

    Protected Sub WebCombo1_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo1.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt



        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub WebCombo2_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo2.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt


        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub ActType_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.ActivityTypesTableAdapter
        Dim dt As New MassChangeDS.ActivityTypesDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt
        ' Response.Write(dt.Count)
    End Sub
    Protected Sub Product_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.ProductsTableAdapter
        Dim dt As New MassChangeDS.ProductsDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt

    End Sub
    Protected Sub Activity_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)

        Dim adap As New MassChangeDSTableAdapters.ActivitiesTableAdapter
        Dim dt As New MassChangeDS.ActivitiesDataTable

        dt = adap.GetData(Session("PlanYear"))

        e.DataSource = dt
    End Sub

    Protected Sub divide_Click(sender As Object, e As ImageClickEventArgs) Handles divide.Click
        Dim TotalMoney As Decimal = Val(TextBox1.Text)
        If TotalMoney > 0 Then
            Dim adap As New FixMoneyLimitTableAdapters.BudgetDetailsTableAdapter
            Dim dataGrid As DataTable
            dataGrid = CType(WebGrid1.DataSource, DataTable)
            Dim money As Decimal
            Dim money2 As Decimal = 0
            For Each row As DataRow In dataGrid.Rows
                If IsDBNull(row.Item("Element9")) = False Then
                    money = row.Item("Element9")
                Else
                    money = 0
                End If

                If money > 0 Then
                    money2 += money
                    adap.Update1Amount(money, row.Item("Id"))
                    row.Item("Amount") = money
                End If
            Next

            Dim moneyP As Decimal
            Dim moneyP2 As Decimal = 0
            Dim moneyToPercen As Decimal = TotalMoney - money2
            Dim money_ As Decimal
            If moneyToPercen > 0 Then
                For Each row As DataRow In dataGrid.Rows
                    If IsDBNull(row.Item("Element9")) = False Then
                        money_ = row.Item("Element9")
                    Else
                        money_ = 0
                    End If
                    If IsDBNull(row.Item("Element8")) = False Then
                        moneyP = row.Item("Element8")
                    Else
                        moneyP = 0
                    End If

                    If moneyP > 0 Then
                        moneyP2 += ((moneyP / 100) * moneyToPercen)
                        adap.Update1Amount(((moneyP / 100) * moneyToPercen), row.Item("Id"))
                        row.Item("Amount") = money
                    End If
                    If moneyP <= 0 And money_ <= 0 Then
                        adap.Update1Amount(0, row.Item("Id"))
                        row.Item("Amount") = 0
                    End If
                Next
            Else
                Alert("วงเงินรวมต้องมากกว่าวงเงินทั้งหมด")
                Exit Sub
            End If

            Dim moneyTotal As Decimal = money2 + moneyP2
            TextBox2.Text = moneyTotal.ToString("n2")
            Label4.Text = ((moneyTotal / TotalMoney) * 100).ToString("n2") & "% เทียบกับปริมาณที่ตั้งไว้"

            logger.Info("User " & Session("users") & " do assign credit limit")
        Else
            Alert("กรุณากรอกวงเงินรวมให้ถูกต้อง")
            Exit Sub
        End If

        WebGrid1.ClearCachedDataSource()
        'WebGrid1.DataBind()
        WebGrid1.ClientAction.Refresh()
        WebGrid1.RebindDataSource()
    End Sub

    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource
        'Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        'Dim dt As New FundCenterParent.SelectorDataTable
        'Dim dt2 As New FundCenterParent.SelectorDataTable
        'Dim sql = ""
        'Dim prefil As String = ""
        'prefil = Session("prefilter")
        'sql += " WHERE 1 = 1 "
        'sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        'If prefil <> "" Then
        '    sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        'End If
        'sql += "ORDER BY Grouppath"
        'adap.GetDataByFilter(dt2, sql)
        'dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        'dt.Merge(dt2)
        ''dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        'e.DataSource = dt

        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable
        dt = adap.GetData(Session("PlanYear"))
        e.DataSource = dt
    End Sub
    Protected Sub WebCombo4_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)
        Dim adap As New MassChangeDSTableAdapters.CmmtsTableAdapter
        Dim dt As New MassChangeDS.CmmtsDataTable
        dt = adap.GetData(Session("PlanYear"))
        e.DataSource = dt
    End Sub
End Class

